package booyah.validation;

import booyah.application.User;
import booyah.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

public class LoginValidator {


    public static User validate(User user, UserService userService, Errors errors) {
        if (!StringUtils.hasLength(user.getEmail()) || !StringUtils.hasLength(user.getPassword())) {
            errors.rejectValue("email", "required", "Email address and password are required");
        }
        User validatedUser = null;
        if (!errors.hasErrors()) {
            validatedUser = userService.authenticate(user.getEmail(), user.getPassword());
            if (validatedUser == null) {
                errors.rejectValue("email", "invalid", "Email and Password are not valid");
            }
        }
        return validatedUser;
    }
}
